
package com.kugou.game.sdk.core;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.kugou.framework.base.LogUtil;
import com.kugou.framework.v4.Fragment;
import com.kugou.game.sdk.entity.BasePayRequestParams;
import com.kugou.game.sdk.entity.Coupon;
import com.kugou.game.sdk.entity.ExchangeRatio;
import com.kugou.game.sdk.entity.KubiPayRequestParams;
import com.kugou.game.sdk.entity.MobilePayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.entity.RechargeDiscount;
import com.kugou.game.sdk.entity.UnionPayRequestParams;
import com.kugou.game.sdk.interfaces.OnAliPayListener;
import com.kugou.game.sdk.interfaces.OnCardPayListener;
import com.kugou.game.sdk.interfaces.OnKubiPayListener;
import com.kugou.game.sdk.interfaces.OnPayCheckListener;
import com.kugou.game.sdk.interfaces.OnRequestExchageInfoListener;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.OnSmsPayListener;
import com.kugou.game.sdk.protocol.CardPayTask;
import com.kugou.game.sdk.protocol.CardPayTask.CardPayHttpResponse;
import com.kugou.game.sdk.protocol.KubiPayTask;
import com.kugou.game.sdk.protocol.KubiPayTask.KubiPayHttpResponse;
import com.kugou.game.sdk.protocol.MobilePayTask;
import com.kugou.game.sdk.protocol.MobilePayTask.MobilePayHttpResponse;
import com.kugou.game.sdk.protocol.PayCheckTask;
import com.kugou.game.sdk.protocol.PayCheckTask.PayCheckHttpResponse;
import com.kugou.game.sdk.protocol.RequestCouponInfoTask;
import com.kugou.game.sdk.protocol.RequestCouponInfoTask.CouponInfoResponse;
import com.kugou.game.sdk.protocol.RequestExchangeInfoTask;
import com.kugou.game.sdk.protocol.RequestExchangeInfoTask.ExchangeRatioResponse;
import com.kugou.game.sdk.protocol.SMSPayTask;
import com.kugou.game.sdk.protocol.SMSPayTask.SMSPayHttpResponse;
import com.kugou.game.sdk.ui.activity.UPPayBridgeActivity;
import com.kugou.game.sdk.utils.FileUtil;
import com.kugou.game.sdk.utils.ThreadTaskManager;
import com.switfpass.pay.MainApplication;
import com.switfpass.pay.activity.PayPlugin;
import com.switfpass.pay.bean.RequestMsg;

/**
 * 描述:支付
 * 
 * @author chenys
 * @since 2013-12-2 下午8:13:13
 */
public class PayManager {

    private final static String msgNetWorkAbnormal = "网络异常，请检查网络连接！";

    private final static String PAY_MANAGER_CONFIGS = "payManagerConfigs";

    private final static String PAY_LAST_MODE = "lastMode";

    private final static String NO_NEED_SHOW_SECURITY_SETTING = "NO_NEED_SHOW_SECURITY_SETTING";

    private static ExchangeRatioResponse sRatioResponse = null;

    private static int sLastRechargeMode = -1;

    private static boolean sIsShowRedPoint = false;

    /**
     * 红点是否在显示的时候，被用户点击，而消失掉
     */
    private static boolean sIsChangeShowRedPoint = false;

    // 游戏代金券
    private static ArrayList<Coupon> sGameCouponInfos = null;

    // 游币代金券
    private static ArrayList<Coupon> sYouBiCouponInfos = null;

    private static boolean sCouponInfosRequestFailed = false;

    private static boolean sShowYoubiRechargeCoupon = false;

    /**
     * 请求支付宝支付
     * 
     * @param activity
     * @param alipayMSG 支付宝请求参数
     * @param listener 回调接口
     */
    public static void payByAli(final Activity activity, String alipayMSG,
            final OnAliPayListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnAliPayListener can't be null");
        }
        // 这里接收支付结果，支付宝手机端同步通知
        Handler mAliPayHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                try {
                    String strRet = (String) msg.obj;
                    switch (msg.what) {
                        case 1: {
                            // 处理交易结果
                            try {
                                // 获取交易状态码，具体状态代码请参看文档
                                String tradeStatus = "resultStatus={";
                                int imemoStart = strRet.indexOf("resultStatus=");
                                imemoStart += tradeStatus.length();
                                int imemoEnd = strRet.indexOf("};memo=");
                                tradeStatus = strRet.substring(imemoStart, imemoEnd);

                                // 先验签通知 客户端没有那个签名，由服务器提供，所以这部不执行了
                                if (tradeStatus.equals("9000")) {
                                    // 判断交易状态码，只有9000表示交易成功
                                    listener.onSuccess();

                                } else if (TextUtils.equals(tradeStatus, "8000")) {
                                    // 判断resultStatus 为非“9000”则代表可能支付失败
                                    // “8000”
                                    // 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                                    listener.onFailed("正在处理交易，请稍候", "-1");
                                } else {
                                    // 这是支付宝sdk返回的交易失败
                                    listener.onFailed(getAliPayResultMsg(activity, tradeStatus),
                                            tradeStatus);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                // 这是支付宝sdk返回的交易失败
                                listener.onFailed("支付宝交易失败，发生了异常", "-1");
                            }
                        }
                            break;
                    }

                    super.handleMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        // 构造PayTask 对象
        PayTask alipay = new PayTask(activity);
        // 该方法查看支付宝插件版本
        // LogUtil.d("dax", "当前支付宝插件版本为：----" +
        // alipay.getVersion());

        // 调用支付接口
        String result = alipay.pay(alipayMSG);
        Message msg = new Message();
        msg.what = 1;
        msg.obj = result;
        mAliPayHandler.sendMessage(msg);

    }

    /**
     * 微信支付
     * 
     * @param activity
     * @param money
     * @param tokenid
     * @param orderid
     */
    public static void payByWeixin(Activity activity, double money, String tokenid, String orderid) {
        RequestMsg msg = new RequestMsg();
        msg.setMoney(money);
        msg.setTokenId(tokenid);
        msg.setOutTradeNo(orderid);
        // 微信wap支付
        msg.setTradeType(MainApplication.PAY_WX_WAP);
        PayPlugin.unifiedH5Pay(activity, msg);
    }

    private static String getAliPayResultMsg(Context context, String code) {
        String[] resultCode = context.getResources().getStringArray(
                context.getResources().getIdentifier("kg_alipay_result_code", "array",
                        context.getPackageName()));
        String[] resultMsg = context.getResources().getStringArray(
                context.getResources().getIdentifier("kg_alipay_result_msg", "array",
                        context.getPackageName()));
        HashMap<String, String> hashMap = new HashMap<String, String>();
        for (int i = 0; i < resultCode.length; i++) {
            hashMap.put(resultCode[i], resultMsg[i]);
        }
        return hashMap.get(code);
    }

    /**
     * 请求电话卡支付
     * 
     * @param requestParams 电话卡支付参数实体类
     * @param listener 回调接口
     */
    public static void payByMobileCard(MobilePayRequestParams requestParams,
            OnCardPayListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnCardPayListener can't be null");
        }
        MobilePayTask httpTask = new MobilePayTask();
        MobilePayHttpResponse response = httpTask.request(requestParams);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                // 返回数据result中，code返回1代表成功，不过判断orderid是否为空来判断是否成功更为准确
                if (!TextUtils.isEmpty(response.getResult_orderid())) {
                    listener.onSuccess(response.getResult_orderid());
                } else {
                    listener.onFailed(response.getResult_msg());
                }
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 游戏点卡充值
     * 
     * @param requestParams
     * @param listener
     */
    public static void payByGameCard(MobilePayRequestParams requestParams,
            OnCardPayListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnCardPayListener can't be null");
        }
        CardPayTask httpTask = new CardPayTask();
        CardPayHttpResponse response = httpTask.request(requestParams);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                // 返回数据result中，code返回1代表成功，不过判断orderid是否为空来判断是否成功更为准确
                if (!TextUtils.isEmpty(response.getResult_orderid())) {
                    listener.onSuccess(response.getResult_orderid());
                } else {
                    listener.onFailed(response.getResult_msg());
                }
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 短信支付请求
     * 
     * @param params
     * @param listener
     */
    public static void payBySMS(BasePayRequestParams params, OnSmsPayListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnSmsPayListener can't be null");
        }
        SMSPayTask httpTask = new SMSPayTask();
        SMSPayHttpResponse response = httpTask.request(params);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                // 返回数据result中，code返回1代表成功，不过判断orderid是否为空来判断是否成功更为准确
                if (!TextUtils.isEmpty(response.getResult_orderid())) {
                    listener.onSuccess(response.getResult_orderid(), response.getResult_url(),
                            response.getResult_params(), response.getResult_desc());
                } else {
                    listener.onFailed(response.getResult_msg());
                }
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 请求游币支付
     * 
     * @param requestParams 游币支付参数实体类
     * @param listener 回调接口
     */
    public static void payByKubi(KubiPayRequestParams requestParams, OnKubiPayListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnKubiPayListener can't be null");
        }
        KubiPayTask httpTask = new KubiPayTask();
        KubiPayHttpResponse response = httpTask.request(requestParams);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                // 1是兑换成功，2是代金券全额抵扣
                if ("1".equals(response.getResult_code()) || "2".equals(response.getResult_code())) {
                    listener.onSuccess(response.getLeftKubi());
                } else {
                    listener.onFailed(response.getResult_message());
                }
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 请求获取：支付状态结果，目前只有电话充值卡会调用该接口
     * @param username
     * @param orderId 订单号
     * @param chargeType 支付类型
     * @param listener 回调接口
     */
    public static void checkPay(String username, String orderId, int chargeType,
            OnPayCheckListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnPayCheckListener can't be null");
        }
        PayCheckTask httpTask = new PayCheckTask();
        PayCheckHttpResponse response = httpTask.request(username, orderId, chargeType);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                // 返回数据result中，code返回1代表成功
                if ("1".equals(response.getResult_code())) {
                    listener.onSuccess();
                } else if ("0".equals(response.getResult_code())) {
                    listener.onWaiting();
                } else {
                    listener.onFailed(response.getResult_prompt());
                }
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 使用银联进行支付
     * 
     * @param activity
     * @param requestCode startActivityForResult(intent,
     *            requestCode)的requestCode
     * @param requestParams 银联支付的请求参数实体类
     */
    public static void payByUnion(Activity activity, int requestCode,
            UnionPayRequestParams requestParams) {
        Intent intent = new Intent(activity, UPPayBridgeActivity.class);
        intent.putExtra("request_params", requestParams);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 使用银联进行支付(供fragment使用)
     * 
     * @param fragment
     * @param requestCode startActivityForResult(intent,
     *            requestCode)的requestCode
     * @param requestParams 银联支付的请求参数实体类
     */
    public static void payByUnion(Fragment fragment, int requestCode,
            UnionPayRequestParams requestParams) {
        Intent intent = new Intent(fragment.getActivity(), UPPayBridgeActivity.class);
        intent.putExtra("request_params", requestParams);
        fragment.startActivityForResult(intent, requestCode);
    }

    private static int sRetryNum = 0;

    private static boolean sIsInNextRequesting = false;

    /**
     * 请求兑换比例
     */
    public static void requestExchangeRatio() {
        ThreadTaskManager.excuteTask(new Runnable() {

            @Override
            public void run() {
                sRetryNum++;
                requestExchangeRatio("-1", new OnRequestExchageInfoListener() {
                    @Override
                    public void onFailed(String errorMsg) {
                        if (sRetryNum < 2) {
                            requestExchangeRatio();
                        }
                    }
                });

            }
        });
    }

    /**
     * 请求游戏的兑换比例
     * @param chargeType
     * @param listener
     */
    private static void requestExchangeRatio(String chargeType,
            OnRequestExchageInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestExchageInfoListener can't be null");
        }

        LogUtil.d("requestExchangeRatio", "request exchange ratio");

        RequestExchangeInfoTask task = new RequestExchangeInfoTask();
        ExchangeRatioResponse response = task.request(chargeType);
        if (response != null && response.isOk()) {
            sRatioResponse = response;
            sRetryNum = 0;

            if (hasYoubiRechargepreferential()) {
                if (!sIsChangeShowRedPoint) {
                    sIsShowRedPoint = true;
                }

                LogUtil.d("requestExchangeRatio", "next request = "
                        + sRatioResponse.getDiscount().getNextRequestLeftTime());

                // 根据后端返回下次请求剩余时间设置下次请求
                if (sRatioResponse.getDiscount().getNextRequestLeftTime() > 0
                        && !sIsInNextRequesting) {
                    sIsInNextRequesting = true;
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            // 倒计时完成的时候，把优惠信息隐藏
                            sRatioResponse.setDiscount(null);
                            // 兑换比例发生变化的时候，发送广播，通知刷新界面
                            SDKControler.getContext().sendBroadcast(
                                    new Intent(SDKActions.ACTION_YOUBI_RATIO_CHANGE));

                            sIsInNextRequesting = false;
                            requestExchangeRatio();

                        }
                    }, sRatioResponse.getDiscount().getNextRequestLeftTime() * 1000);
                }
            } else {
                sIsShowRedPoint = false;
            }

            // 兑换比例发生变化的时候，发送广播，通知刷新界面
            SDKControler.getContext().sendBroadcast(
                    new Intent(SDKActions.ACTION_YOUBI_RATIO_CHANGE));

        } else if (response != null && response.getPrompt() != null) {
            listener.onFailed(response.getPrompt());
        } else {
            listener.onFailed(msgNetWorkAbnormal);
        }
    }

    /**
     * 获得优惠可获得的游币
     * 
     * @param money
     * @return
     */
    public static int getExchangeKubiExtraNum(int money) {
        double extra = 0;
        if (sRatioResponse != null && sRatioResponse.getDiscount() != null && money > 0) {
            int type = sRatioResponse.getDiscount().getDiscountType();
            ArrayList<ExchangeRatio> ratioList = sRatioResponse.getDiscount().getmRatio();

            if (type == RechargeDiscount.TYPE_1) {
                for (int i = 0; i < ratioList.size(); i++) {
                    if (money < ratioList.get(i).getMax() && money >= ratioList.get(i).getMin()) {
                        extra = ratioList.get(i).getPercent();
                        break;
                    }
                }
            } else if (type == RechargeDiscount.TYPE_2) {
                for (int i = 0; i < ratioList.size(); i++) {
                    if (money < ratioList.get(i).getMax() && money >= ratioList.get(i).getMin()) {
                        extra = ratioList.get(i).getPercent() * money;
                        break;
                    }
                }
            }

        }
        return (int) (extra * getYoubiRatio());
    }

    /**
     * 是否有游币优惠信息
     * 
     * @return
     */
    public static boolean hasYoubiRechargepreferential() {
        return sRatioResponse != null && sRatioResponse.getDiscount() != null;
    }

    /**
     * @return 是否显示游币兑换代金券
     */
    public static boolean showYoubiRechargeCoupon() {
        return sShowYoubiRechargeCoupon;
    }

    /**
     * 获取游币充值的优惠信息简短标题
     * 
     * @return
     */
    public static String getKubiRechargePreferentialTitle() {
        if (sRatioResponse != null && sRatioResponse.getDiscount() != null) {
            return sRatioResponse.getDiscount().getTitle();
        }

        return "";
    }

    /**
     * 获取游币充值的优惠信息次级标题
     * 
     * @return
     */
    public static String getKubiRechargePreferentialSubTitle() {
        if (sRatioResponse != null && sRatioResponse.getDiscount() != null) {
            return sRatioResponse.getDiscount().getSubTitle();
        }

        return "";
    }

    /**
     * 获取游币充值优惠详情
     * 
     * @return
     */
    public static String getKubiRechargePreferentialDetail() {
        if (sRatioResponse != null && sRatioResponse.getDiscount() != null) {
            return sRatioResponse.getDiscount().getDetail();
        }
        return "";
    }

    /**
     * 获取各支付方式的兑换比例
     * 
     * @param chargeType
     * @param money
     * @return
     */
    public static double getExchangeRatio(int chargeType, int money) {
        if (sRatioResponse != null) {
            HashMap<String, ArrayList<ExchangeRatio>> ratioMap = sRatioResponse.getRatioMap();
            ArrayList<ExchangeRatio> ratioList = null;
            switch (chargeType) {
                case ChargeType.TYPE_PHONE:// 电话卡
                    ratioList = ratioMap.get("charge_28");
                    break;
                case ChargeType.TYPE_ALIPAY:// 支付宝
                    ratioList = ratioMap.get("charge_29");
                    break;
                case ChargeType.TYPE_UNIONPAY:// 银联
                    ratioList = ratioMap.get("charge_34");
                    break;
                case ChargeType.TYPE_KUBI:// 游币兑换
                    ratioList = ratioMap.get("charge_0");
                    break;
                case ChargeType.TYPE_GAME_CARD:
                    ratioList = ratioMap.get("charge_43");
                    break;
                case ChargeType.TYPE_SMS:
                    ratioList = ratioMap.get("charge_44");
                    break;
                case ChargeType.TYPE_YIPAY:
                    ratioList = ratioMap.get("charge_48");
                    break;
                case ChargeType.TYPE_WEIXIN:
                    ratioList = ratioMap.get("charge_50");
                    break;
            }
            // 获取各支付方式的兑换比例
            return getPercent(ratioList, money);

        }

        return 1;
    }

    /**
     * 计算不同支付方式兑换后能获得的游戏币
     * 
     * @param chargeType
     * @param moneyNum
     * @return
     */
    public static String getExchangeMoneyNum(int chargeType, int moneyNum) {
        if (sRatioResponse != null) {
            HashMap<String, ArrayList<ExchangeRatio>> ratioMap = sRatioResponse.getRatioMap();
            // 获取各支付方式的兑换比例
            double chargeTypeRatio = getExchangeRatio(chargeType, moneyNum);
            // 获取游戏的兑换比例
            ArrayList<ExchangeRatio> gameList = ratioMap.get("game");
            double gameRatio = getPercent(gameList, moneyNum);
            // 获得可兑换的游戏币总额
            double total = moneyNum * chargeTypeRatio * gameRatio;
            if (total > 0) {
                return (int) total + sRatioResponse.getCoinName();
            }
        }
        return "";
    }

    public static int getSmsPercent() {
        if (sRatioResponse != null) {
            HashMap<String, ArrayList<ExchangeRatio>> ratioMap = sRatioResponse.getRatioMap();
            ArrayList<ExchangeRatio> ratioList = null;

            ratioList = ratioMap.get("charge_44");
            // 获取游戏的兑换比例
            if (ratioList != null && ratioList.size() > 0) {
                return (int) (ratioList.get(0).getPercent() * 100);
            }
        }
        return 50;
    }

    /**
     * 获取充值卡、游戏点卡能得到多少游币
     * 
     * @param money
     * @param mode
     * @return
     */
    public static String getExchangeNum(int money, int mode) {
        double canExchangeNum = money;
        if (sRatioResponse != null) {
            HashMap<String, ArrayList<ExchangeRatio>> ratioMap = sRatioResponse.getRatioMap();
            ArrayList<ExchangeRatio> ratioList = null;
            switch (mode) {
                case ChargeType.TYPE_PHONE:
                    ratioList = ratioMap.get("charge_28");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        for (ExchangeRatio ratio : ratioList) {
                            if (ratio.getMin() <= money && ratio.getMax() >= money) {
                                canExchangeNum = money * ratio.getPercent() * getYoubiRatio();
                            }
                        }
                    }
                    break;
                case ChargeType.TYPE_GAME_CARD:
                    ratioList = ratioMap.get("charge_43");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        for (ExchangeRatio ratio : ratioList) {
                            if (ratio.getMin() <= money && ratio.getMax() >= money) {
                                canExchangeNum = money * ratio.getPercent() * getYoubiRatio();
                            }
                        }
                    }
                default:
                    break;
            }
        }

        canExchangeNum += getExchangeKubiExtraNum(money);

        return canExchangeNum + "游币";
    }

    /**
     * 获取各充值方式的兑换比例提示
     * 
     * @return
     */
    public static String getRechargeExchangeTip(int chargeType, boolean isRechargeYoubi) {
        if (sRatioResponse != null) {
            HashMap<String, ArrayList<ExchangeRatio>> ratioMap = sRatioResponse.getRatioMap();
            ArrayList<ExchangeRatio> gameList = ratioMap.get("game");
            StringBuffer sb = new StringBuffer();
            ArrayList<ExchangeRatio> ratioList = null;
            String unitStr = sRatioResponse.getCoinName();
            if (isRechargeYoubi) {
                unitStr = "游币";
            }
            double ratioValue = getPercent(gameList, 1);
            if (isRechargeYoubi) {
                ratioValue = getYoubiRatio();
            }

            switch (chargeType) {
                case ChargeType.TYPE_PHONE:
                    ratioList = ratioMap.get("charge_28");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        for (ExchangeRatio ratio : ratioList) {
                            if (ratio.getMin() == 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("面值≤" + ratio.getMax() + "元，").append(
                                        "10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("面值>" + (ratio.getMin() - 1) + "元，")
                                        .append("面值≤" + ratio.getMax() + "元，")
                                        .append("10元 = "
                                                + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() == Integer.MAX_VALUE) {
                                sb.append("面值>" + (ratio.getMin() - 1) + "元，").append(
                                        "10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else {// 只有一个比例
                                sb.append("10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                        + unitStr);
                            }
                        }
                    }
                    break;
                case ChargeType.TYPE_ALIPAY:
                    ratioList = ratioMap.get("charge_29");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        sb.append(getRatioByList(ratioList, gameList, isRechargeYoubi, ratioValue));
                    }
                    break;
                case ChargeType.TYPE_UNIONPAY:
                    ratioList = ratioMap.get("charge_34");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        sb.append(getRatioByList(ratioList, gameList, isRechargeYoubi, ratioValue));
                    }
                    break;
                case ChargeType.TYPE_YIPAY:
                    ratioList = ratioMap.get("charge_48");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        sb.append(getRatioByList(ratioList, gameList, isRechargeYoubi, ratioValue));
                    }
                    break;
                case ChargeType.TYPE_KUBI:
                    ratioList = ratioMap.get("charge_0");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        for (ExchangeRatio ratio : ratioList) {
                            if (ratio.getMin() == 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("充值 ≤ " + ratio.getMax() + "游币，").append(
                                        "1游币 = " + (int) (ratio.getPercent() * ratioValue)
                                                + sRatioResponse.getCoinName() + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("充值 > " + (ratio.getMin() - 1) + "游币，")
                                        .append("充值 ≤ " + ratio.getMax() + "游币，")
                                        .append("1游币 = " + (int) (ratio.getPercent() * ratioValue)
                                                + sRatioResponse.getCoinName() + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() == Integer.MAX_VALUE) {
                                sb.append("充值 > " + (ratio.getMin() - 1) + "游币，").append(
                                        "1游币 = " + (int) (ratio.getPercent() * ratioValue)
                                                + sRatioResponse.getCoinName() + "\n");
                            } else {// 只有一个比例
                                sb.append("1游币 = " + (int) (ratio.getPercent() * ratioValue)
                                        + sRatioResponse.getCoinName());
                            }
                        }
                    }
                    break;

                case ChargeType.TYPE_GAME_CARD:
                    ratioList = ratioMap.get("charge_43");
                    // 获取游戏的兑换比例
                    if (ratioList != null && ratioList.size() > 0) {
                        for (ExchangeRatio ratio : ratioList) {
                            if (ratio.getMin() == 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("面值≤" + ratio.getMax() + "元，").append(
                                        "10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() != Integer.MAX_VALUE) {
                                sb.append("面值>" + (ratio.getMin() - 1) + "元，")
                                        .append("面值≤" + ratio.getMax() + "元，")
                                        .append("10元 = "
                                                + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else if (ratio.getMin() != 0 && ratio.getMax() == Integer.MAX_VALUE) {
                                sb.append("面值>" + (ratio.getMin() - 1) + "元，").append(
                                        "10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                                + unitStr + "\n");
                            } else {// 只有一个比例
                                sb.append("10元 = " + (int) (10 * ratio.getPercent() * ratioValue)
                                        + unitStr);
                            }
                        }
                    }
                    break;
            }

            String tips = sb.toString();
            if (tips.contains("\n")) {
                int last = tips.lastIndexOf("\n");
                return tips.substring(0, last);
            } else {
                return tips;
            }

        }
        return "";
    }

    /**
     * 支付宝、银联 从兑换比例数据解析出来比例字符串
     * 
     * @param ratioList
     * @param gameList
     * @param isRechargeYoubi
     * @param ratioValue
     * @return
     */
    private static String getRatioByList(ArrayList<ExchangeRatio> ratioList,
            ArrayList<ExchangeRatio> gameList, boolean isRechargeYoubi, double ratioValue) {
        StringBuffer sb = new StringBuffer();
        for (ExchangeRatio ratio : ratioList) {
            if (ratio.getMin() == 0 && ratio.getMax() != Integer.MAX_VALUE) {
                sb.append("充值 ≤ " + ratio.getMax() + "元，").append(
                        "1元 = " + (int) (ratio.getPercent() * ratioValue) + isRechargeYoubi + "\n");
            } else if (ratio.getMin() != 0 && ratio.getMax() != Integer.MAX_VALUE) {
                sb.append("充值 > " + (ratio.getMin() - 1) + "元，")
                        .append("充值 ≤ " + ratio.getMax() + "元，")
                        .append("1元 = " + (int) (ratio.getPercent() * ratioValue) + isRechargeYoubi
                                + "\n");
            } else if (ratio.getMin() != 0 && ratio.getMax() == Integer.MAX_VALUE) {
                sb.append("充值 > " + (ratio.getMin() - 1) + "元，").append(
                        "1元 = " + (int) (ratio.getPercent() * ratioValue) + isRechargeYoubi + "\n");
            } else {// 只有一个比例
                sb.append("1元 = " + (int) (ratio.getPercent() * ratioValue) + isRechargeYoubi);
            }
        }

        return sb.toString();
    }

    /**
     * 根据金额获得在不同支付方式里的兑换比例
     * 
     * @param ratioList
     * @param moneyNum
     * @return
     */
    private static double getPercent(ArrayList<ExchangeRatio> ratioList, int moneyNum) {
        if (ratioList != null && ratioList.size() > 0) {
            for (ExchangeRatio ratio : ratioList) {
                if (moneyNum >= ratio.getMin() && moneyNum <= ratio.getMax()) {
                    return ratio.getPercent();
                }
            }
        }
        return 0;
    }

    /**
     * 获取人民币与游币的兑换比例
     * 
     * @return
     */
    public static int getYoubiRatio() {
        if (sRatioResponse != null) {
            return sRatioResponse.getYoubiRatio();
        }

        return 100;
    }

    /**
     * 获取最后充值成功方式
     * 
     * @return
     */
    public static int getLastRechargeMode() {
        if (sLastRechargeMode != -1) {
            return sLastRechargeMode;
        }

        if (!FileUtil.isSDCardAvailable()) {
            return -1;
        }

        int mode = -1;
        if (FileUtil.isExist(FolderManager.RECHARGE_MODE_FILE_PATH)) {
            byte[] data = FileUtil.getFileData(FolderManager.RECHARGE_MODE_FILE_PATH);
            if (data != null && data.length > 0) {
                mode = getModeByJsonData(new String(data));
                sLastRechargeMode = mode;
            }
        }
        return mode;
    }

    /**
     * 保存充值成功的方式
     * 
     * @param mode 方式
     * @return
     */
    public static boolean setLastRechargeMode(int mode) {
        sLastRechargeMode = mode;

        if (!FileUtil.isSDCardAvailable()) {
            return false;
        }

        try {
            if (!FileUtil.isExist(FolderManager.RECHARGE_MODE_FILE_PATH)) {
                FileUtil.createFile(FolderManager.RECHARGE_MODE_FILE_PATH, false);
            }

            FileUtil.writeFile(FolderManager.RECHARGE_MODE_FILE_PATH, createPayJsonDataByMode(mode)
                    .toString(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 由最后充值方式生成payManagerConfig的json数据
     * 
     * @param mode
     * @return
     */
    private static String createPayJsonDataByMode(int mode) {
        JSONObject payObject = new JSONObject();
        JSONObject object = new JSONObject();
        try {
            object.put(PAY_LAST_MODE, mode);
            payObject.put(PAY_MANAGER_CONFIGS, object);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return payObject.toString();
    }

    /**
     * 由本地数据获取最后充值方式
     * 
     * @param data
     * @return
     */
    private static int getModeByJsonData(String data) {
        int mode = 0;
        JSONObject object;
        try {
            object = new JSONObject(data);
            mode = object.getJSONObject(PAY_MANAGER_CONFIGS).getInt(PAY_LAST_MODE);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return mode;
    }

    public static void setPaySecurityTipNeedShow(String username) {
        if (!FileUtil.isSDCardAvailable()) {
            return;
        }
        try {
            StringBuffer sb = null;
            String key = NO_NEED_SHOW_SECURITY_SETTING + username;
            if (!FileUtil.isExist(FolderManager.SECURITY_SETTING_FILE_PATH)) {
                FileUtil.createFile(FolderManager.SECURITY_SETTING_FILE_PATH, false);
                sb = new StringBuffer(key);
                byte[] data = sb.toString().getBytes();
                FileUtil.rewriteData(FolderManager.SECURITY_SETTING_FILE_PATH, data);
            } else {
                byte[] b = FileUtil.getFileData(FolderManager.SECURITY_SETTING_FILE_PATH);
                String list = new String(b);
                if (!list.contains(key)) {
                    sb = new StringBuffer(list);
                    sb.append(",");
                    sb.append(key);
                    byte[] data = sb.toString().getBytes();
                    FileUtil.rewriteData(FolderManager.SECURITY_SETTING_FILE_PATH, data);
                }
            }
        } catch (Exception e) {
        }
    }

    public static boolean getPaySecurityTipNeedShow(String username) {
        if (!FileUtil.isSDCardAvailable()
                || !FileUtil.isExist(FolderManager.SECURITY_SETTING_FILE_PATH)) {
            return true;
        }

        if (FileUtil.isExist(FolderManager.SECURITY_SETTING_FILE_PATH)) {
            try {
                String key = NO_NEED_SHOW_SECURITY_SETTING + username;
                byte[] data = FileUtil.getFileData(FolderManager.SECURITY_SETTING_FILE_PATH);
                String setting = new String(data);
                if (setting.contains(key)) {// 如果SD卡记录过该账号，说明已经设置过该账号不需要再弹窗提示
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static boolean isCouponInfosRequestFailed() {
        return sCouponInfosRequestFailed;
    }

    public static void setCouponInfosRequestFailed(boolean couponInfosRequestFailed) {
        PayManager.sCouponInfosRequestFailed = couponInfosRequestFailed;
    }

    public static void requestCouponInfo(final boolean isYoubiRecharge,
            final OnRequestListener listener) {
        ThreadTaskManager.excuteTask(new Runnable() {

            public void run() {
                if (isYoubiRecharge) {
                    sYouBiCouponInfos = null;
                    requestCouponInfo(listener, 2);
                } else {
                    sGameCouponInfos = null;
                    requestCouponInfo(listener, 1);
                }
            }
        });

    }

    public static void requestCouponInfo(final OnRequestListener listener) {
        ThreadTaskManager.excuteTask(new Runnable() {

            @Override
            public void run() {
                sYouBiCouponInfos = null;
                sGameCouponInfos = null;
                requestCouponInfo(listener, 2);
                requestCouponInfo(listener, 1);

            }
        });

    }

    private static void requestCouponInfo(OnRequestListener listener, int type) {
        CouponInfoResponse response = new RequestCouponInfoTask().request(type);
        if (response != null) {
            if (response.isOk()) {
                sGameCouponInfos = response.getCouponInfos();
                // 请求游戏代金券才修改是否显示游币兑换界面代金券显示的标志
                if (type == 1) {
                    sShowYoubiRechargeCoupon = response.isShowYoubiRechargeCoupon();
                }
                setCouponInfosRequestFailed(false);
                if (listener != null)
                    listener.onSuccess();
            } else {
                LogUtil.e(response.getPrompt() == null ? "" : response.getPrompt());
                setCouponInfosRequestFailed(true);
                if (listener != null)
                    listener.onFailed(response.getPrompt());
            }
        } else {
            LogUtil.e("请求代金券失败");
            setCouponInfosRequestFailed(true);
            if (listener != null)
                listener.onFailed("请求代金券失败");
        }
    }

    public static boolean isShowRedPoint() {
        return sIsShowRedPoint;
    }

    public static void changeShowRedPoint(boolean isShowRedPoint) {
        sIsChangeShowRedPoint = true;
        PayManager.sIsShowRedPoint = isShowRedPoint;
    }

    public static ArrayList<Coupon> getCouponInfos(boolean isYoubiRecharge) {
        if (isYoubiRecharge) {
            return sYouBiCouponInfos;
        } else {
            return sGameCouponInfos;
        }
    }

    public static ArrayList<Coupon> getCouponInfos(boolean isYoubiRecharge, int rechargeValue) {
        if (isYoubiRecharge) {
            return getCouponInfosWithValue(sYouBiCouponInfos, rechargeValue);
        } else {
            return getCouponInfosWithValue(sGameCouponInfos, rechargeValue);
        }
    }

    private static ArrayList<Coupon> getCouponInfosWithValue(ArrayList<Coupon> coupons, int value) {
        if (coupons == null)
            return null;

        ArrayList<Coupon> result = new ArrayList<Coupon>();
        for (int i = 0; i < coupons.size(); i++) {
            if (coupons.get(i).getMoneyLimit() <= value) {
                result.add(coupons.get(i));
            }
        }

        return result;
    }
}
